import React, { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import type { Variants } from 'framer-motion';
import axios from 'axios';
import { useLocation, useNavigate } from 'react-router-dom';
import BackButton from '../components/BackButton';

interface Transaction {
  id: string;
  trans_code: string;
  trans_sn: string;
  rrn: string;
  orderid: string;
  pan: string;
  trans_amt: string;
  trans_date: string;
  trans_time: string;
  merno: string;
  terminal: string;
  resp_code: string;
  bank_date: string;
  created_at: string;
}

interface RefundResult {
  trans_code: string;
  bank_date: string;
  resp_code: string;
  trans_sn: string;
  rrn: string;
  orderid: string;
  pan: string;
  error_msg?: string;
}

const CEF: React.FC = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const [refundAmount, setRefundAmount] = useState('');
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState<RefundResult | null>(null);
  const [error, setError] = useState<string | null>(null);

  // 获取从交易列表传递过来的原交易信息
  const originalTransaction = location.state?.originalTransaction as Transaction;

  // 如果没有原交易信息，返回交易列表
  useEffect(() => {
    if (!originalTransaction) {
      navigate('/transactions');
    }
  }, [originalTransaction, navigate]);

  // 动画配置
  const containerVariants: Variants = {
    hidden: { opacity: 0, y: 20 },
    visible: {
      opacity: 1,
      y: 0,
      transition: {
        duration: 0.6,
        ease: [0.43, 0.13, 0.23, 0.96]
      }
    }
  };

  const formatAmount = (amount: string): string => {
    const numAmount = parseInt(amount, 10) / 100;
    return numAmount.toFixed(2);
  };

  const formatDateTime = (date: string, time: string): string => {
    return `${date.slice(0, 4)}-${date.slice(4, 6)}-${date.slice(6, 8)} ${time.slice(0, 2)}:${time.slice(2, 4)}:${time.slice(4, 6)}`;
  };

  const handleRefund = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!refundAmount) {
      setError('请输入退货金额');
      return;
    }

    const refundAmountInCents = Math.round(parseFloat(refundAmount) * 100);
    const originalAmountInCents = parseInt(originalTransaction.trans_amt, 10);

    if (refundAmountInCents > originalAmountInCents) {
      setError('退货金额不能大于原交易金额');
      return;
    }

    if (refundAmountInCents <= 0) {
      setError('退货金额必须大于0');
      return;
    }

    setLoading(true);
    setError(null);
    setResult(null);

    try {
      // 生成退货订单号
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
      const refundOrderId = `REFUND${year}${month}${day}${random}`;

      const requestData = {
        pan: originalTransaction.pan,
        appid: '01',
        trans_amt: String(refundAmountInCents).padStart(11, '0'),
        org_trans_sn: originalTransaction.trans_sn,
        org_rrn: originalTransaction.rrn,
        merno: originalTransaction.merno,
        terminal: originalTransaction.terminal,
        pay_order: refundOrderId  // 添加退货订单号
      };

      console.log('发送退货请求:', requestData);
      
      const response = await axios.post('/api/cef', requestData);
      console.log('退货响应:', response.data);
      
      if (response.data.resp_code !== '0') {
        setError(response.data.error_msg || '退货失败');
      } else {
        setResult(response.data);
      }
    } catch (err: any) {
      console.error('退货请求错误:', err);
      const errorMessage = err.response?.data?.detail || err.response?.data?.error_msg || '退货失败，请稍后重试';
      setError(typeof errorMessage === 'string' ? errorMessage : '退货失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  if (!originalTransaction) {
    return null;
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-[#eaf2ff] via-[#f0f7ff] to-[#f8fbff] py-12 px-4 sm:px-6 lg:px-8 relative overflow-hidden">
      <BackButton />
      
      {/* 背景装饰 */}
      <div className="fixed inset-0 -z-10 overflow-hidden">
        <div className="absolute -top-40 -left-40 w-80 h-80 bg-blue-200 rounded-full mix-blend-multiply filter blur-3xl opacity-20 animate-blob"></div>
        <div className="absolute -bottom-40 -right-40 w-80 h-80 bg-purple-200 rounded-full mix-blend-multiply filter blur-3xl opacity-20 animate-blob animation-delay-2000"></div>
      </div>

      <motion.div
        className="max-w-4xl mx-auto"
        initial="hidden"
        animate="visible"
        variants={containerVariants}
      >
        <div className="text-center mb-10">
          <h1 className="text-4xl font-bold bg-clip-text text-transparent bg-gradient-to-r from-indigo-500 to-purple-500">
            单卡额度退货
          </h1>
          <p className="mt-3 text-xl text-gray-600">
            输入退货金额（可以小于等于原交易金额）
          </p>
        </div>

        <div className="bg-white/60 backdrop-blur-xl border border-white/30 rounded-2xl p-8 shadow-[0_8px_32px_rgba(0,0,0,0.08)]">
          {/* 原交易信息 */}
          <div className="mb-8 grid grid-cols-1 md:grid-cols-2 gap-6">
            <div className="bg-gray-50/50 rounded-xl p-6 space-y-4">
              <h3 className="text-lg font-medium text-gray-900">原交易信息</h3>
              <div className="space-y-3">
                <div>
                  <p className="text-sm text-gray-500">交易时间</p>
                  <p className="text-base font-medium text-gray-900">
                    {formatDateTime(originalTransaction.trans_date, originalTransaction.trans_time)}
                  </p>
                </div>
                <div>
                  <p className="text-sm text-gray-500">交易金额</p>
                  <p className="text-base font-medium text-red-600">
                    -¥{formatAmount(originalTransaction.trans_amt)}
                  </p>
                </div>
                <div>
                  <p className="text-sm text-gray-500">卡号</p>
                  <p className="text-base font-medium text-gray-900 font-mono">
                    {originalTransaction.pan}
                  </p>
                </div>
                <div>
                  <p className="text-sm text-gray-500">交易流水号</p>
                  <p className="text-base font-medium text-gray-900 font-mono">
                    {originalTransaction.trans_sn}
                  </p>
                </div>
              </div>
            </div>

            {/* 退货表单 */}
            <div className="bg-white/50 rounded-xl p-6">
              <h3 className="text-lg font-medium text-gray-900 mb-4">退货信息</h3>
              <form onSubmit={handleRefund} className="space-y-6">
                <div>
                  <label htmlFor="refundAmount" className="block text-sm font-medium text-gray-700 mb-2">
                    退货金额
                  </label>
                  <div className="relative">
                    <span className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-500">¥</span>
                    <input
                      type="text"
                      id="refundAmount"
                      value={refundAmount}
                      onChange={(e) => setRefundAmount(e.target.value)}
                      className="block w-full pl-8 pr-4 py-3 rounded-xl bg-white/50 border border-gray-200 focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-all duration-200 outline-none"
                      placeholder={`最大可退 ${formatAmount(originalTransaction.trans_amt)}`}
                    />
                  </div>
                </div>

                <button
                  type="submit"
                  disabled={loading}
                  className="w-full py-3 px-6 text-white bg-gradient-to-r from-indigo-500 to-purple-500 rounded-xl hover:from-indigo-600 hover:to-purple-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition-all duration-200 disabled:opacity-50"
                >
                  {loading ? '处理中...' : '确认退货'}
                </button>
              </form>
            </div>
          </div>

          <AnimatePresence mode="wait">
            {/* 错误提示 */}
            {error && (
              <motion.div
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -10 }}
                className="mt-6 p-4 bg-red-50 rounded-xl border border-red-100"
              >
                <p className="text-red-800 text-sm">{error}</p>
              </motion.div>
            )}

            {/* 退货结果 */}
            {result && (
              <motion.div
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -10 }}
                className="mt-6 space-y-4"
              >
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <div className="bg-white/50 backdrop-blur-sm rounded-xl p-4 border border-white/30">
                    <p className="text-sm text-gray-500 mb-1">退货流水号</p>
                    <p className="text-lg font-medium text-gray-900">{result.trans_sn}</p>
                  </div>
                  <div className="bg-white/50 backdrop-blur-sm rounded-xl p-4 border border-white/30">
                    <p className="text-sm text-gray-500 mb-1">系统参考号</p>
                    <p className="text-lg font-medium text-gray-900">{result.rrn}</p>
                  </div>
                </div>
                
                <div className="bg-white/50 backdrop-blur-sm rounded-xl p-4 border border-white/30">
                  <p className="text-sm text-gray-500 mb-2">退货状态</p>
                  <span className={`inline-flex items-center px-3 py-1 rounded-full text-sm font-medium ${
                    result.resp_code === '0'
                      ? 'bg-green-100 text-green-800'
                      : 'bg-red-100 text-red-800'
                  }`}>
                    {result.resp_code === '0' ? '退货成功' : '退货失败'}
                  </span>
                  {result.error_msg && result.resp_code !== '0' && (
                    <p className="mt-2 text-sm text-gray-600">{result.error_msg}</p>
                  )}
                </div>
              </motion.div>
            )}
          </AnimatePresence>
        </div>
      </motion.div>
    </div>
  );
};

export default CEF; 